from django.template import RequestContext, loader
from core import get_page_from_request
from django.http import HttpResponse
import functools

def render_to(template=None, mimetype=None, response_class=HttpResponse):
    def decorator(view_func):
        def decorated(request, *args, **kwargs):
            context = view_func(request, *args, **kwargs)
            if not isinstance(context, dict):
                return context
            if template is None:
                template_ = get_page_from_request(request).content.template
            else:
                template_ = template

            return response_class(
                loader.render_to_string(
                    template_,
                    context,
                    context_instance=RequestContext(request),
                ),
                mimetype=mimetype
            )
        return functools.update_wrapper(decorated, view_func)

    return decorator
